// src/ChatRoom.js
import React, { useEffect, useState, useRef } from 'react';
import ReconnectingWebSocket from 'reconnecting-websocket';

const ChatRoom = ({ roomId }) => {
    const [messages, setMessages] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const socketRef = useRef(null);


    
    useEffect(() => {
        socketRef.current = new ReconnectingWebSocket(`http://localhost:5000/${roomId}`);   //websocket进行连接

        socketRef.current.onopen = () => {
            console.log('Connected to WebSocket');   //事件监听 连接成功
        };

        socketRef.current.onmessage = (event) => {    //事件监听 接收到消息
            const newMessage = JSON.parse(event.data);
            setMessages((prevMessages) => [...prevMessages, newMessage]);
        };

        return () => {      //组件销毁时关闭websocket连接
            socketRef.current.close();
        };
    }, [roomId]);

    const ids = [1, 2, 3, 4, 5, 6]
    const id = ids[Math.floor(Math.random() * ids.length)];   //随机生成用户id

    const handleSend = () => {     //发送消息
        if (inputValue.trim()) {
            socketRef.current.send(JSON.stringify({
                type: 'message',
                content: inputValue,
                sender: id, // Replace with actual user ID
                timestamp: new Date().toISOString(),
            }));
            setInputValue('');
        }
    };

    return (
        <div>
            <div className="chat-log">
                <h1>Group Chat</h1>
                {messages.map((msg, index) => (
                    <div style={{ fontSize: '20px' }} key={index}>
                        <strong>{msg.sender}:</strong> {msg.content} <small>{new Date(msg.timestamp).toLocaleTimeString()}</small>
                    </div>
                ))}
            </div>
            <div className="input-container">
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' ? handleSend() : null}
                />
                <button onClick={handleSend}>Send</button>
            </div>

        </div>
    );
};

export default ChatRoom;